package edu.upenn.seas.peerreview.smui
import edu.upenn.seas.peerreview.{Id, Sink}
import edu.upenn.seas.peerreview.smui.RGRTestMessages._



/* ********************************************************** */
// Coordinator

class RGRTestManager(myId:Id, t:Sink.T) extends BSHandler(myId, t) {

  var resourcesAvailable = 10

  var Q: List[Envelope] = Nil

  def handle (e: Envelope) { 
    e.contents match {
      case ReleaseResource(n) =>
        resourcesAvailable += n
      case RequestResource(n) =>
        Q = e :: Q
    }

    def removeFirstLessThanX(x: Int, l: List[Envelope]): (Envelope, List[Envelope]) = {
      l match {
        case h :: t =>
          h match {
            case Envelope(from, to, RequestResource(n)) if (x>=n) =>
              (h, t)
            case _ => {
              val rec = removeFirstLessThanX(x, t)
              (rec._1, h::rec._2)
            }
          }
        case _ =>
          (null, Nil)
      }
    }

    while (true) {
      val res = removeFirstLessThanX(resourcesAvailable, Q)
      Q = res._2
      if (res._1 == null) return;
      res match {
        case (Envelope(f, t, RequestResource(n)), _) =>
          send(f, GrantResource(n))
          resourcesAvailable -= n
      }
    }
  }
}

